//
//  DOTableViewController.m
//  DooiooOnline
//
//  Created by koki on 14-11-7.
//  Copyright (c) 2014年 dooioo. All rights reserved.
//
#import "SRRefreshView.h"
#import "HDTableViewController.h"

@interface HDTableViewController ()
@property BOOL decelerateEnd;
@property (strong, nonatomic)SRRefreshView *slimeView;
@end

@implementation HDTableViewController
@synthesize dataArray,curentIndex,enableRefresh,enableRequest,selected;

- (SRRefreshView *)slimeView
{
    if (_slimeView == nil) {
        _slimeView = [[SRRefreshView alloc] init];
        _slimeView.delegate = (id)self;
        _slimeView.upInset = 0;
        _slimeView.slimeMissWhenGoingBack = YES;
        _slimeView.slime.bodyColor = [UIColor grayColor];
        _slimeView.slime.skinColor = [UIColor grayColor];
        _slimeView.slime.lineWith = 1;
        _slimeView.slime.shadowBlur = 4;
        _slimeView.slime.shadowColor = [UIColor grayColor];
    }
    return _slimeView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.dataArray=nil;
    self.prevIndex=0;
    self.pageNum=1;
    self.decelerateEnd=YES;
    self.enableRequest=NO;
    self.enableRefresh=YES;
    
    self.arrowUpView=[[ArrowView alloc] initWithFrame:CGRectMake(0,APPFRAME.size.height,APPFRAME.size.width, 50)];
    self.arrowUpView.type=ArrowsType_Request;
    self.arrowUpView.hidden=YES;
    self.arrowUpView.state=ArrowsSate_Normal;
    [self.view addSubview:self.arrowUpView];
    [self.tableView addSubview:self.slimeView];
}

-(void)setEbableRefresh:(BOOL)value
{
    enableRefresh=value;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([self.delegate respondsToSelector:@selector(scrollViewDidScroll:)])
    {
        [self.delegate performSelector:@selector(scrollViewDidScroll:) withObject:nil];
    }
    
    if (enableRefresh)
    {
         [_slimeView scrollViewDidScroll];
    }
    if(self.enableRequest)
    {
        float offsetMax=self.tableView.contentSize.height-self.tableView.frame.size.height;
        float offsetY=scrollView.contentOffset.y;
        if (self.pageNum>=self.totalPagesNum||offsetMax<0)
        {
            return;
        }
        
        self.arrowUpView.frame=CGRectMake(0,self.tableView.contentSize.height,APPFRAME.size.width, 50);
        self.arrowUpView.hidden=NO;
        if (offsetMax>0 && offsetY>=offsetMax
            &&self.decelerateEnd
            &&self.arrowUpView.state!=ArrowsSate_Start)
        {
            self.decelerateEnd=NO;
            self.arrowUpView.state=ArrowsSate_Start;
            [UIView animateWithDuration:0.3 animations:^{
                self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 50, 0);
                scrollView.contentOffset=CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y+50);
            }
            completion:^(BOOL finished)
            {
               [self.delegate pullTableView:self.tableView isNextPage:YES];
            }];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.decelerateEnd=YES;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (enableRefresh)
    {
        [_slimeView scrollViewDidEndDraging];
    }
}

#pragma mark - slimeRefresh delegate
//刷新列表
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    if ([self.delegate respondsToSelector:@selector(pullRefreshRequest)])
    {
        [self.delegate pullRefreshRequest];
    }
}

-(void)dealloc
{
    dataArray=nil;
    selected=nil;
}

-(void)setCurentIndex:(int)index
{
    curentIndex=index;
    self.selected=nil;
    [self.tableView reloadData];
}

-(void)setDataArray:(NSArray*)array
{
    self.selected=nil;
    curentIndex=-1;
    dataArray=[[NSMutableArray alloc] initWithArray:array];
    [self.tableView reloadData];
    
    if (self.arrowUpView.state==ArrowsSate_Start)
    {
        self.arrowUpView.state=ArrowsSate_End;
        [UIView animateWithDuration:0.3 animations:^{
            self.tableView.contentInset = UIEdgeInsetsZero;
        }completion:^(BOOL finished)
         {
            self.arrowUpView.hidden=YES;
        }];
        
        [self performBlock:^{
            self.arrowUpView.state=ArrowsSate_Normal;
            self.decelerateEnd=YES;
        } afterDelay:0.3];
    }
    else
    {
        self.arrowUpView.hidden=YES;
        [self.slimeView endRefresh];
    }
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* indentifer=@"indentiferCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifer];
    if (cell==nil)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifer];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!tableView.isEditing) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    self.selected=[self.dataArray objectAtIndex:indexPath.row];
    curentIndex=(int)indexPath.row;
    if([self.delegate respondsToSelector:@selector(tableView: didSelectRowAtIndexPath:)])
    {
        [self.delegate performSelector:@selector(tableView: didSelectRowAtIndexPath:) withObject:tableView withObject:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([self.delegate respondsToSelector:@selector(tableView: didDeselectRowAtIndexPath:)])
    {
        [self.delegate performSelector:@selector(tableView: didDeselectRowAtIndexPath:) withObject:tableView withObject:indexPath];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.cellHeight<=0)
    {
        self.cellHeight=44;
    }
    return self.cellHeight;
}

@end



@interface ArrowView ()
@property DOImageView* arrowImgView;
@property UILabel* tipLabel;
@property UIActivityIndicatorView* actIndicator;
@end

@implementation ArrowView
@synthesize text,state;

-(id)initWithFrame:(CGRect)frame
{
    self=[super initWithFrame:frame];
    if (self)
    {
        self.arrowImgView=[[DOImageView alloc] initWithFrame:CGRectZero];
        self.arrowImgView.imgURLStr=@"refresh_arrow.png";
        
        self.tipLabel=[HDUtil UILabelWithText:text fontSize:14];
        self.tipLabel.textColor=[UIColor darkGrayColor];
        self.tipLabel.frame=CGRectMake(0, 0,APPFRAME.size.width,50);
        self.tipLabel.textAlignment=NSTextAlignmentCenter;
        self.actIndicator=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.actIndicator.frame=CGRectMake(0, 0, 30, 30);
        self.actIndicator.hidden=YES;
        [self addSubview:self.actIndicator];
        [self addSubview:self.tipLabel];
        [self addSubview:self.arrowImgView];
    }
    return self;
}
-(void)setText:(NSString *)value
{
    text=[value copy];
    self.tipLabel.text=text;
}

-(void)updateUI
{
    switch (state)
    {
        case ArrowsSate_Normal:
        {
            
            [UIView animateWithDuration:0.3 animations:^{
                
                CGFloat angle=(self.type==ArrowsType_Refresh)?M_PI*2:M_PI;
                self.arrowImgView.transform=CGAffineTransformMakeRotation(angle);
                self.arrowImgView.hidden=NO;
                self.text=(self.type==ArrowsType_Refresh)?@"下拉刷新":@"上拉加载下一页";
            }];
        }
            break;
        case ArrowsSate_Start:
        {
            self.arrowImgView.hidden=YES;
            self.text=@"正在载入...";
        }
            break;
        case ArrowsSate_Ready:
        {
            [UIView animateWithDuration:0.3 animations:^{
                self.arrowImgView.transform=CGAffineTransformMakeRotation(M_PI);
                self.arrowImgView.hidden=NO;
                self.text=@"松手刷新";
            }];
        }
            break;
        case ArrowsSate_End:
        {
            self.arrowImgView.hidden=YES;
            self.actIndicator.hidden=YES;
            self.text=@"加载结束";
            NSLog(@"ArrowsSate_End");
        }
            break;
            
        default:
            break;
    }
    
    if(self.delegate!=nil)
    {
        [self.delegate arrowView:self state:state];
    }
    
    CGSize size=[HDUtil getSizeWithText:self.text fontSize:14];
    self.arrowImgView.frame=CGRectMake((self.frame.size.width-(size.width+50.0))/2.0,(self.frame.size.height-30)/2.0, 22, 30);
    self.actIndicator.frame=self.arrowImgView.frame;
    
    if (ArrowsSate_End!=state)
    {
      self.actIndicator.hidden=!self.arrowImgView.hidden;
    }
    if (self.actIndicator.hidden)
    {
        [self.actIndicator stopAnimating];
    }
    else
    {
        [self.actIndicator startAnimating];
    }

}

-(void)setState:(ArrowsSate)value
{
    state=value;
    [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];
    
}
@end





